
//
//  ZHLonInViewController.swift
//  999999新浪微博
//
//  Created by 陈华 on 15/12/19.
//  Copyright © 2015年 华锐. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD




class ZHLonInViewController: UIViewController,UIWebViewDelegate {

    
    
    override func loadView() {
         view = web
        setWebView()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        web.delegate = self
        setNavItem()
    }
    
    func setNavItem(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "fillClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Done, target: self, action: "cancelClick")
    }
    
    func setWebView(){
        let request = NSURLRequest(URL: NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=1972890934&redirect_uri=http://www.baidu.com//")!)
        web.loadRequest(request)
    }
    
    
    func cancelClick(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func fillClick(){
        // 创建js代码
        let js = "document.getElementById('userId').value='13710107262'; document.getElementById('passwd').value='chenzhenhua.1014';"
        //让web来执行js代码
        web.stringByEvaluatingJavaScriptFromString(js)
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
      SVProgressHUD.showInfoWithStatus("正在加载", maskType: SVProgressHUDMaskType.Black)
    }
    
    //MARK: - webView的代理  判断是否加载网络。
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let absolute = request.URL!.absoluteString
        if  !absolute.hasPrefix(ZHNetWorkingController.netWorking.redirect_uri) {//没有点击登录
            return true
        }
        
        let code = request.URL?.query
        if let cd = code{//code有值
            let stingCode = "code="
            if  cd.hasPrefix(stingCode){//点击授权
                let cdNSStirng = cd as NSString
                let cdNew = cdNSStirng.substringFromIndex(stingCode.characters.count)
                 loadAccessToken(cdNew)//加载访问令牌
            }else{//点击取消
                cancelClick()
            }
        }else{
            print("code没有值")
        }
        return  false
    }
    
    func loadAccessToken(codeNew:String){
        
        ZHNetWorkingController.netWorking.loadAccess_token(codeNew) { (resultt, error) -> () in
            
            
            guard error == nil && resultt != nil else{//没有数据
                
                return SVProgressHUD.showErrorWithStatus("你的网络不给力")
            }
            
            let userAccount  =  ZHUserAccount(dict: resultt!)
            
            let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last
            let fullPath = path! + "/name"
            NSKeyedArchiver.archiveRootObject(userAccount, toFile: fullPath)
            
           // let obj  = NSKeyedUnarchiver.unarchiveObjectWithFile(fullPath)
           // print("obj == \(obj)")
        }
        
    }
    
    ///懒加载
    lazy var web = UIWebView()
    
}








